<?php
/**
 * QQAS - share your knowledge to the world!
 * 
 * @author		xiaochong0302 <xiaochong0302@gmail.com>
 * @copyright	Copyright (c) 2011, Koogua Studio.
 * @license		http://www.qqas.org/user_guide/license.html
 * @link		http://www.qqas.org
 * @since		Version 1.0
 * @filesource
 */
 
class InvitationModel extends Model 
{
	
	
	/**
	 * 检查邀请码合法性
	 *
	 * @param string $key
	 * @return bool
	 */
	public function checkKey($key)
	{
		$map = array('key' => trim($key));
		$result = $this->where($map)->find();
		if (empty($result) || (0 != $result['expire_time'] && $result['expire_time'] < time()) || (0 == $result['status']))
		{
			return false;
		}
		return true;
	}
	
	
	/**
	 * 生成邀请码
	 *
	 * @param int $userID
	 * @return null
	 */
	public function makeKey($userID)
	{
		$expiration = get_site_config('invite_expiration');
		$key = strtoupper(md5(time().rand(1000,9999)));
		$data = array(
			'user_id' => $userID,
			'key' => $key,
			'create_time' => time(),
			'expire_time' => !empty($expiration) ? time() + $expiration * 86400 : 0,
			'status' => 1,
		);
		$this->add($data);
	}
	
	
	/**
	 * 通过邀请码查找邀请码信息
	 *
	 * @param string $key
	 * @return  array $user
	 */
	public function getInvitationByKey($key)
	{
		$map = array('key' => $key);
		$invite = $this->where($map)->find();
		return $invite;
	}
	
	
	/**
	 * 通过邀请码查找邀请人
	 *
	 * @param string $key
	 * @return  array $user
	 */
	public function getInviterByKey($key)
	{
		$User = D('User');
		$map = array('key' => $key);
		$invite = $this->where($map)->find();
		$user = $User->find($invite['user_id']);
		return $user;
	}
	
	
	/**
	 * 本周可用邀请码数
	 *
	 * @param int $userID
	 * @return int 
	 */
	public function getCredits($userID)
	{
		$maxWeekInvites = get_site_config('max_invites_per_week');
    	$stampToday = strtotime(date('Y-m-d'));
    	$weekToday  = date('N');
    	$stampWeekStart = $stampToday - $weekToday * 86400;
    	$stampWeekEnd   = $stampToday + (8 - $weekToday) * 86400;
    	
    	$map = array(
    		'user_id' => $userID,
    		'create_time' => array('between', array($stampWeekStart, $stampWeekEnd)),
    	);
    	$weekCount = $this->where($map)->count();
    	
    	$availableInvites = $maxWeekInvites - $weekCount;
    	return $availableInvites > 0 ? $availableInvites : 0;
	}
	
}

/* End of file InvitationModel.class.php */
/* Location: ./App/Lib/Model/InvitationModel.class.php */